package com.example.blockbreaker;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Database(entities = {HealthData.class, CravingRecord.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    private static volatile AppDatabase INSTANCE;
    private static final int NUMBER_OF_THREADS = 4;

    // 创建线程池用于数据库操作
    static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public abstract HealthDataDao healthDataDao();
    public abstract CravingDao cravingDao();

    // 提供Executor访问方法
    public static Executor getExecutor() {
        return databaseWriteExecutor;
    }

    // 版本1到版本2的迁移（添加trigger字段）
    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            // 创建临时表
            database.execSQL("CREATE TABLE craving_records_new (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "level INTEGER NOT NULL, " +
                    "trigger TEXT, " +
                    "timestamp INTEGER NOT NULL)");

            // 复制数据
            database.execSQL("INSERT INTO craving_records_new (id, level, timestamp) " +
                    "SELECT id, level, timestamp FROM craving_records");

            // 删除旧表
            database.execSQL("DROP TABLE craving_records");

            // 重命名新表
            database.execSQL("ALTER TABLE craving_records_new RENAME TO craving_records");
        }
    };

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(
                                    context.getApplicationContext(),
                                    AppDatabase.class,
                                    "health_tracker.db")
                            .addCallback(new RoomDatabase.Callback() {
                                @Override
                                public void onCreate(@NonNull SupportSQLiteDatabase db) {
                                    super.onCreate(db);
                                    Log.d("Database", "数据库和表已创建");
                                }
                            })
                            .fallbackToDestructiveMigration() // 开发阶段使用
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}
